import { createRouter, createWebHistory } from 'vue-router'
import { routes, roleNameList } from './routerMap'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // 引入样式
import { useUserStore, useRouterStore } from '@/store'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由白名单
const routesWhiteList = ['Login', 'Home', 'Layout', 'NotRoleView']

NProgress.configure({ showSpinner: true }) // 显示右上角螺旋加载提示

router.beforeEach((to, from, next) => {
  // routerStore
  const routerStore = useRouterStore()

  // userStore
  const userStore = useRouterStore()

  // 判断当前路由是否在白名单里
  if (routesWhiteList.indexOf(to.name) != -1) {
    NProgress.start() // 开启进度条
    // some code ...
    NProgress.done() // 关闭进度条
    console.log('to-', to)
    routerStore.currentMenuSort = to.meta.sort

    // 判断tabs存在不存在当前tab
    let tabNames = []
    routerStore.tabsList.forEach((r) => {
      tabNames.push(r.name)
    })
    if (tabNames.indexOf(to.name) == -1) {
      if (to.name != 'Login' && to.name != 'NotRoleView') {
        routerStore.tabsList.push({
          title: to.meta.title,
          path: to.path,
          name: to.name,
          sort: to.meta.sort,
        })
      }
    }

    next()
  } else {
    let roleNl = []
    let role = 1
    console.log('userStore.currentUserRole', userStore.currentUserRole)
    // console.log('localStorage', localStorage.getItem('roleMenus'))
    let roleMenus = JSON.parse(localStorage.getItem('roleMenus'))
    let userRole = JSON.parse(localStorage.getItem('currentUserRole'))

    if (userRole) {
      role = userRole
    }
    console.log('role', role)
    console.log('roleNameList', roleNameList)

    if (roleNameList) {
      roleNl = roleNameList.filter((rnl) => {
        return rnl.role == role
      })[0].roleNames
    } else {
      console.log(roleNameList)
    }
    console.log('roleNl', roleNl)

    // 判断有无权限
    if (roleNl.indexOf(to.name) != -1) {
      NProgress.start() // 开启进度条
      // some code ...
      NProgress.done() // 关闭进度条
      console.log('to-', to)
      routerStore.currentMenuSort = to.meta.sort

      // 判断tabs存在不存在当前tab
      let tabNames = []
      routerStore.tabsList.forEach((r) => {
        tabNames.push(r.name)
      })
      if (tabNames.indexOf(to.name) == -1) {
        if (to.name != 'Login') {
          routerStore.tabsList.push({
            title: to.meta.title,
            path: to.path,
            name: to.name,
            sort: to.meta.sort,
          })
        }
      }

      next()
    } else {
      ElMessage({
        message: '您暂无该权限',
        type: 'error',
        duration: 2000,
      })
      router.push({
        path: '/notRoleView',
      })
      // router.back()
    }
  }
})

export default router
